package com.ysgsignin.wxinfo.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ysgsignin.wxinfo.domain.WxStudntimages;
import com.ysgsignin.wxinfo.service.IWxStudntimagesService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Component
public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    @Autowired
    private IWxStudntimagesService wxStudntimagesService;


    /**
     * @param file      文件
     * @param imageName 学生学号
     * @return
     */
    @Transactional
    public synchronized String upLoad(File file, String imageName) {
        logger.info("------OSS图片文件上传开始--------" + file.getName());
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        //这里endpoint 在你的bucket列表->点击你的bucket->点击概览中间就有，下面有截图
//        System.out.println("获取到的Point为:" + endpoint);
        String accessKeyId = "xxxx";    //accessKeyId 、accessKeySecret 上面有说到哪里获取
        String accessKeySecret = "xxxxxxxx";
        String bucketName = "studentimage";  //刚才新建的bucket名称
        String fileHost = "images";   //在刚才新建的bucket下面新建一个目录，这就是那个目录的名称
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        // 判断文件
        if (file == null) {
            return null;
        }
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            // 设置文件路径和名称
            String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                //     把上传的oss路径上传到数据库进行保存----微信新增接口---交友
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("osswxaddress", "https://studentimage.oss-cn-shanghai.aliyuncs.com/" + fileUrl);
                WxStudntimages wxStudntimages = new WxStudntimages();
                WxStudntimages OneStudent = wxStudntimagesService.selectWxStudntByNameNoimagesList(imageName);
                wxStudntimages.setImageName(imageName); //学号
                wxStudntimages.setImageUrl(hashMap.get("osswxaddress"));//学号
                if (OneStudent != null) {
                    System.out.println(OneStudent);
//                    更新操作     使用微信接口进行更新操作
                    wxStudntimagesService.wxupdateWxStudntimages(wxStudntimages);
                } else {
//                    新增数据
                    wxStudntimagesService.insertWxStudntimages(wxStudntimages);
                }
                logger.info("------OSS文件上传成功------" + "https://studentimage.oss-cn-shanghai.aliyuncs.com/" + fileUrl);
            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return null;
    }

    public synchronized String compareupLoad(File file, String imageName) {
        logger.info("------OSS图片文件上传开始--------" + file.getName());
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        //这里endpoint 在你的bucket列表->点击你的bucket->点击概览中间就有，下面有截图
//        System.out.println("获取到的Point为:" + endpoint);
        String accessKeyId = "xxxxxx";    //accessKeyId 、accessKeySecret 上面有说到哪里获取
        String accessKeySecret = "xxx";
        String bucketName = "studentimage";  //刚才新建的bucket名称
        String fileHost = "images";   //在刚才新建的bucket下面新建一个目录，这就是那个目录的名称
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        // 判断文件
        if (file == null) {
            return null;
        }
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String fileUrl = null;
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            // 设置文件路径和名称
            fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return fileUrl;
    }


}
